<template>
  <div class="image-list" style="width: 100%">
    <el-upload
      v-loading="loading"
      action="#"
      ref="uploadRef"
      :before-upload="handleBeforeUpload"
      :http-request="handleUpload"
      :on-exceed="handleOnExceed"
      :show-file-list="false"
      :multiple="multiple"
      :limit="limit"
    >
      <el-button type="success" icon="Grid" @click.stop="openImagesPick">
        {{ $t('common.title.select') }}
      </el-button>
      <el-button type="primary" icon="Upload">
        {{ $t('common.action.upload') }}
      </el-button>
    </el-upload>
    <ul class="el-upload-list el-upload-list--text">
      <li
        v-for="(item, index) in imageList"
        :key="index"
        class="el-upload-list__item is-success"
      >
        <div style="display: flex; justify-content: space-between">
          <div>
            <span
              style="cursor: pointer"
              @click="handlePictureCardPreview(item.url)"
            >
              <el-icon><Document /></el-icon>
              {{ item.url }}
            </span>
          </div>
          <div>
            <span style="margin-right: 20px; cursor: pointer">
              <el-icon @click.stop="handleRemove(item)"><Close /></el-icon>
            </span>
          </div>
        </div>
      </li>
    </ul>
  </div>
  <!-- 图片预览 -->
  <el-image-viewer
    v-if="viewVisible"
    :zoom-rate="1.2"
    :initial-index="initialIndex"
    :url-list="viewFileList"
    @close="closePreview"
  />
  <!-- 文件选择器 -->
  <ra-file-picker
    ref="refFilePicker"
    :multiple="multiple"
    :onlyImage="onlyImage"
    @update="updateSelect"
  />
</template>
<script setup>
/**
 * 单文件，多文件
 * 图片，文件
 * 文件名称列表
 */
import { smartTranslate as $t } from '@/lang';
import { clone } from 'xe-utils';
import AdminFileAPI from '@/api/admin/admin/file';

const props = defineProps({
  modelValue: {
    type: [String, Array],
  },
  onlyImage: {
    type: Boolean,
    default: false,
  },
  multiple: {
    type: Boolean,
    default: false,
  },
  limit: {
    type: Number,
    default: 1,
  },
});

const emit = defineEmits(['update:modelValue']);
const uploadRef = ref();
const imageList = ref(props.modelValue);
const loading = ref(false);
const viewVisible = ref(false);
const viewFileList = ref([]);
const initialIndex = ref(0);

watch(
  () => props.modelValue,
  (newVal) => {
    if (typeof newVal === 'string') {
      imageList.value = newVal ? [{ url: newVal }] : [];
    } else if (Array.isArray(newVal)) {
      if (newVal.length > props.limit) {
        ElMessage.error(
          $t('common.message.upload.max', {
            max: props.limit,
          }),
        );
        return;
      }
      // 如果 newVal 是数组，则遍历数组并创建带有 url 属性的对象数组
      imageList.value = newVal
        .map((item) => {
          if (typeof item === 'string') {
            return { url: item };
          } else if (
            typeof item === 'object' &&
            item !== null &&
            'url' in item
          ) {
            // 如果已经是带有 url 属性的对象，则直接返回
            return { ...item }; // 也可以选择只保留 url 属性，取决于你的需求
          } else {
            console.warn('Invalid item in array:', item);
            return null; // 或者你可以选择跳过无效项
          }
        })
        .filter((item) => item !== null); // 过滤掉无效项
    } else {
      imageList.value = [];
    }
  },
  { immediate: true },
);

const handleBeforeUpload = (event) => {
  if (props.onlyImage && event.type.split('/')[0] != 'image') {
    ElMessage.error($t('common.message.info.only_image'));
    return false;
  }
};

const handleUpload = (options) => {
  loading.value = true;
  AdminFileAPI.add(options.file)
    .then(({ data }) => {
      ElMessage.success(
        $t('common.message.success.general', {
          action: $t('common.action.upload'),
        }),
      );
      if (props.multiple) {
        imageList.value.push(data);
      } else {
        imageList.value = [data];
      }
      updataModelValue(imageList.value);
    })
    .catch(() => {
      ElMessage.error(
        $t('common.message.failed.general', {
          action: $t('common.action.upload'),
        }),
      );
    })
    .finally(() => {
      loading.value = false;
    });
};

const handleOnExceed = (files) => {
  imageList.value = [];
  handleUpload({ file: files[0] });
};

// 删除图片
const handleRemove = (file) => {
  imageList.value = imageList.value.filter((item) => item.url !== file.url);
  updataModelValue(imageList.value);
};

// 打开图片选择界面
// 图片选择
const refFilePicker = ref();
const openImagesPick = () => {
  refFilePicker.value.show();
};
const updateSelect = (data) => {
  updataModelValue(data);
};

// 预览图片
const handlePictureCardPreview = (fileUrl) => {
  if (props.onlyImage) {
    viewFileList.value = imageList.value.map((item) => item.url);
    initialIndex.value = viewFileList.value.findIndex((url) => url === fileUrl);
    viewVisible.value = true;
  }
};
// 关闭预览界面
const closePreview = () => {
  viewVisible.value = false;
};

// 更新V-modelValue
const updataModelValue = (imageList) => {
  const fileList = clone(imageList);
  const urlList = fileList.map((file) => file.url);
  emit('update:modelValue', props.multiple ? urlList : urlList[0]);
};
</script>
